﻿#include "block.h"

Block::Block(const QColor &brushColor, BlockType blockType)
{
    m_brushColor = brushColor;
    m_brushColor.setAlpha(100);
    m_blockType = blockType;
}

QRectF Block::boundingRect() const
{
    int d = ST->blockSideLength();
    return QRectF(-d/2, -d/2, d, d);
}

void Block::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)
    qreal d = ST->blockSideLength();
    painter->setOpacity(m_opacity);
    painter->drawPixmap(-d/2, -d/2, d, d, QPixmap(":/images/block.png"));
    painter->setBrush(m_brushColor);
    //将方块的边界的颜色进行透明化
    QColor penColor = m_brushColor;
    // 将颜色的透明度减小
    penColor.setAlpha(200);
    painter->setPen(penColor);
    //使用当前的笔刷和笔画矩形框
    painter->drawRect(-d/2, -d/2, d, d);
}

QPainterPath Block::shape() const
{
    QPainterPath path;
    //去除笔刷的宽度，这样同一个方块组的方块就不会被检测出碰撞的情况
    path.addRect(boundingRect().adjusted(1, 1, -1, -1));
    return path;
}

/*
 * @Brief:  便捷方式设置方块的相对位置
 * @Detail: --------------------------->
 *          | (1,1) (2,1) (3,1) (4,1)
 *          | (1,2) (2,2) (3,2) (4,2)
 *          | (1,3) (2,3) (3,3) (4,3)
 *          | (1,4) (2,4) (3,4) (4,4)
 *          |
 */
void Block::setCoord(int x, int y)
{
    qreal d = ST->blockSideLength();
    x -= 2;
    y -= 2;
    setPos(x * d, y * d);
}

QPoint Block::coord()
{
    qreal d = ST->blockSideLength();
    int x = this->pos().x() / d;
    int y = this->pos().y() / d;
    return QPoint(x + 2, y +2);
}

BlockType Block::blockType() const
{
    return m_blockType;
}

void Block::setBlockType(BlockType newBlockType)
{
    m_blockType = newBlockType;
}

void Block::moveToAxis(int x, int y)
{
    this->moveBy(20 + x * 40, 790 - 40 * y);
}


/**
 * @brief   设置砖块儿透明度
 * @param   newOpacity -- 透明度[0-1.0]
 */
void Block::setOpacity(double newOpacity)
{
    m_opacity = newOpacity;
}
